<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>购物车 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section class="fade-in">
        <h2>购物车</h2>

        <div class="card">
            <div id="cartList"></div>
        </div>

        <div id="actions" class="flex-between mt-20">
            <div id="msg"></div>
            <button id="checkoutBtn" class="btn secondary hidden">结算</button>
        </div>
    </section>
</div>
<script>
    async function loadCart() {
        try {
            const res = await fetch('/api/carts', {
                credentials: 'include'
            });
            const data = await res.json();

            if (data.length === 0) {
                document.getElementById('cartList').innerHTML = '<p class="text-center">购物车为空</p>';
                document.getElementById('checkoutBtn').classList.add('hidden');
                return;
            }

            let html = '<table><tr><th>商品名称</th><th>单价</th><th>数量</th><th>小计</th><th>库存</th><th>操作</th></tr>';
            let totalPrice = 0;
            let hasStockIssue = false;

            for (const item of data) {
                const product = item.product;
                const subtotal = product.price * item.quantity;
                totalPrice += subtotal;

                // 检查库存状态
                const stockQuantity = product.quantity || 0;
                const isOutOfStock = stockQuantity === 0;
                const isExceedStock = item.quantity > stockQuantity;
                const stockClass = isOutOfStock ? 'stock-error' : (isExceedStock ? 'stock-warning' : '');
                const stockMessage = isOutOfStock ? '无库存' : (isExceedStock ? '库存不足' : `${stockQuantity}`);

                if (isOutOfStock || isExceedStock) {
                    hasStockIssue = true;
                }

                html += `<tr class="${stockClass}">
                <td>${product.name}</td>
                <td>¥${product.price}</td>
                <td class="quantity-cell">
                    <div class="quantity-control">
                        <button class="quantity-btn" onclick="updateQuantity(${item.id}, ${item.quantity - 1})"
                            ${item.quantity <= 1 ? 'disabled' : ''}>-</button>
                        <span class="quantity">${item.quantity}</span>
                        <button class="quantity-btn" onclick="updateQuantity(${item.id}, ${item.quantity + 1})"
                            ${item.quantity >= stockQuantity ? 'disabled' : ''}>+</button>
                    </div>
                </td>
                <td>¥${subtotal}</td>
                <td class="${stockClass}">${stockMessage}</td>
                <td><button class="btn error" onclick="removeItem(${item.id})">删除</button></td>
            </tr>`;
            }

            html += `<tr class="total-row"><td colspan="3">总计</td><td>¥${totalPrice}</td><td colspan="2"></td></tr>`;
            html += '</table>';

            document.getElementById('cartList').innerHTML = html;

            // 如果有库存问题，显示警告并禁用结算按钮
            if (hasStockIssue) {
                document.getElementById('msg').innerHTML = '<div class="warning-msg">部分商品库存不足，请调整数量或删除</div>';
                document.getElementById('checkoutBtn').disabled = true;
            } else {
                document.getElementById('checkoutBtn').disabled = false;
            }

            document.getElementById('checkoutBtn').classList.remove('hidden');
        } catch (e) {
            document.getElementById('cartList').innerHTML = '<div class="error-msg">请先登录</div>';
        }
    }

    async function updateQuantity(itemId, newQuantity) {
        if (newQuantity < 1) return;

        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">更新中...</div>';

            const res = await fetch(`/api/carts/${itemId}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify({ quantity: newQuantity })
            });

            const data = await res.json();

            if (data.error) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error}</div>`;
            } else {
                loadCart();
                document.getElementById('msg').innerHTML = '<div class="success-msg">数量已更新</div>';
                setTimeout(() => document.getElementById('msg').innerHTML = '', 1500);
            }
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">更新失败</div>';
        }
    }

    async function removeItem(itemId) {
        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">删除中...</div>';

            await fetch(`/api/carts/${itemId}`, {
                method: 'DELETE',
                credentials: 'include'
            });

            loadCart();
            document.getElementById('msg').innerHTML = '<div class="success-msg">已删除</div>';
            setTimeout(() => document.getElementById('msg').innerHTML = '', 1500);
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">删除失败</div>';
        }
    }

    document.getElementById('checkoutBtn').onclick = async () => {
        try {
            document.getElementById('msg').innerHTML = '<div class="info-msg">结算中...</div>';

            const res = await fetch('/api/carts/checkout', {
                method: 'POST',
                credentials: 'include'
            });

            const data = await res.json();

            if (data.id) {
                document.getElementById('msg').innerHTML = '<div class="success-msg">下单成功</div>';
                setTimeout(() => {
                    window.location.href = '/orders';
                }, 1000);
            } else {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${data.error || '结算失败'}</div>`;
            }
        } catch (e) {
            document.getElementById('msg').innerHTML = '<div class="error-msg">结算失败</div>';
        }
    };

    loadCart();
</script>
</body>
</html> 